package com.timk.goserver.client.ui.screens;

import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.timk.goserver.client.model.GameInvite;
import com.timk.goserver.client.services.NoSessionException;
import com.timk.goserver.client.ui.widgets.StatusLabel;

/** */
public class InvitePanel extends Composite {
	final StatusPanel statusPanel; // NOPMD - Explicit scoping
	final StatusLabel status; // NOPMD - Explicit scoping
	private final FlexTable table;
	
	/**
	 * Creates an InvitePanel
	 * @param statusPanel the StatusPanel
	 */
	public InvitePanel(StatusPanel statusPanel) {
		this.statusPanel = statusPanel;
		
		VerticalPanel vertPanel = new VerticalPanel();
		
		status = new StatusLabel();
		vertPanel.add(status);
		
		table = new FlexTable();
		table.addStyleName("goserver-Table");
		vertPanel.add(table);
		
		initWidget(vertPanel);
		
		refreshInvites();
	}
	
	final void refreshInvites() {
		MainPanel.msgService.getInvites(new AsyncCallback() {
			public void onSuccess(Object result) {
				status.clear();
				fillTable((List)result);
			}
			
			public void onFailure(Throwable caught) {
				if(caught instanceof NoSessionException) {
					MainPanel.sessionExpired(caught.getMessage());
					return;
				}
				
				status.setError("Couldn't retrieve invites");
			}
		});
	}
	
	final void fillTable(List invites) {
		if(invites.isEmpty()) {
			table.setVisible(false);
			return;
		}
		
		table.setVisible(true);
		
		int numRows = table.getRowCount();
		for(int i = 0; i < numRows; i++) {
			table.removeRow(0);
		}
		
		int curRow = 0;
		for(int i = 0; i < invites.size(); i++) {
			GameInvite invite = (GameInvite)invites.get(i);
			
			table.setText(curRow, 0, "Game invitation received");
			
			Button viewButton = new Button("View");
			viewButton.addClickListener(new ViewListener(invite));
			table.setWidget(curRow, 1, viewButton);
			
			curRow++;
		}
	}
	
	private class ViewListener implements ClickListener {
		private final GameInvite invite;
		
		ViewListener(GameInvite invite) {
			this.invite = invite;
		}
		
		public void onClick(Widget sender) {
			InviteDialog dlg = new InviteDialog(statusPanel, invite, false);
			dlg.show();
		}
	}
}
